const fs = require("fs");
const path = require("path");
const Controller = require("egg").Controller;
const awaitWriteStream = require("await-stream-ready").write;
const sendToWormhole = require("stream-wormhole");

class UploadController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  // 上传单个文件
  async uploadOne() {

    const { ctx } = this;

    const stream = await ctx.getFileStream();

    const filename = path.basename(stream.filename); // 文件名称

    // const extname = path.extname(stream.filename).toLowerCase() // 文件扩展名称

    // 组装参数 stream
    const target = path.join(
      this.config.baseDir,
      "app/public/uploads/logo",
      `${filename}`
    );

    const writeStream = fs.createWriteStream(target);

    // 文件处理，上传到云存储等等
    try {
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
      await sendToWormhole(stream);

      throw err;
    }

    const url = `/public/uploads/logo/${filename}`;

    // 设置响应内容和响应状态码
    ctx.helper.success({ ctx, res: { url } });
  }

  // 上传多个文件
  async multiple() {
    const { ctx } = this;
    const parts = ctx.multipart();

    const files = [];

    let part; // parts() return a promise
    while ((part = await parts()) != null) {
      if (part.length) {
        // 如果是数组的话是 filed
        // console.log('field: ' + part[0])
        // console.log('value: ' + part[1])
        // console.log('valueTruncated: ' + part[2])
        // console.log('fieldnameTruncated: ' + part[3])
      } else {
        if (!part.filename) {
          // 这时是用户没有选择文件就点击了上传(part 是 file stream，但是 part.filename 为空)
          // 需要做出处理，例如给出错误提示消息
          return;
        }

        const filename = part.filename.toLowerCase(); // 文件名称
        // const extname = path.extname(part.filename).toLowerCase() // 文件扩展名称

        const target = path.join(
          this.config.baseDir,
          "app/public/uploads/logo",
          `${filename}`
        );
        const writeStream = fs.createWriteStream(target);
        // 文件处理，上传到云存储等等
        try {
          await awaitWriteStream(part.pipe(writeStream));
        } catch (err) {
          // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
          await sendToWormhole(part);
          throw err;
        }

        files.push({
          url: `/public/uploads/logo/${filename}`,
        });
      }
    }
    ctx.helper.success({ ctx, res: files });
  }
}

module.exports = UploadController;
